import numpy as np
import cv2 as cv
import sys

def putMultiLineText(org_img, text, org, fontFace=cv.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(255,255,255), thickness=1, lineType=cv.LINE_AA):
    """
    在图像上绘制多行文本
    """
    img = org_img.copy()
    x, y = org
    lines = []
    # 分割文本为多行
    for line in text.split('\n'):
        lines.append(line)

    # 逐行绘制文本
    for line in lines:
        cv.putText(img, line, (x, y), fontFace, fontScale, color, thickness, lineType)
        # 根据字体大小调整 y 坐标以实现换行
        y += int(fontScale * 30)  

    return img

help_str = """
w: thresh += 10
s: thresh -= 10

1: THRESH_BINARY
2: THRESH_BINARY_INV
3: THRESH_TRUNC
4: THRESH_TOZERO
5: THRESH_TOZERO_INV

q: exit
"""

if __name__ == "__main__":
    file = "../../res/121.jpg"
    if len(sys.argv) > 1:
        file = sys.argv[1]
    img = cv.resize(cv.imread(file),None, fx=0.5, fy=0.5)
    # 1.获取灰度图
    gray_img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

    # 2.显示 按键操作说明
    text_gray_img = putMultiLineText(gray_img, help_str, (10, 10), color=(0, 255, 0))
    cv.imshow("text_gray_img", text_gray_img)

    thresh = 100
    maxval = 255
    threshold_type = cv.THRESH_BINARY
    while True:
        ret, thresh_img = cv.threshold(gray_img, thresh, maxval, threshold_type)
        cv.imshow("thresh_img", thresh_img)
        key = cv.waitKey(0)
        if key == ord("q"):
            break
        elif key == ord("w"):
            thresh += 10
            thresh = min(255, thresh)
        elif key == ord("s"):
            thresh -= 10
            thresh = max(0, thresh)
        elif key == ord("1"):
            threshold_type = cv.THRESH_BINARY
        elif key == ord("2"):
            threshold_type = cv.THRESH_BINARY_INV
        elif key == ord("3"):
            threshold_type = cv.THRESH_TRUNC
        elif key == ord("4"):
            threshold_type = cv.THRESH_TOZERO
        elif key == ord("5"):
            threshold_type = cv.THRESH_TOZERO_INV
        print(f"thresh:{thresh}, threshold_type:{threshold_type}")

    cv.destroyAllWindows()
